/**
 * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.tms.web;

import java.text.SimpleDateFormat;
import java.util.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;

import com.jeeplus.common.utils.excel.ObjectExcelView;
import com.jeeplus.common.utils.excel.PageData;
import com.jeeplus.modules.tms.importEntity.ResourceImport;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.google.common.collect.Lists;
import com.jeeplus.common.utils.DateUtils;
import com.jeeplus.common.config.Global;
import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.core.persistence.Page;
import com.jeeplus.core.web.BaseController;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.common.utils.excel.ExportExcel;
import com.jeeplus.common.utils.excel.ImportExcel;
import com.jeeplus.modules.tms.entity.Resource;
import com.jeeplus.modules.tms.service.ResourceService;

/**
 * 承运商Controller
 * @author dhw
 * @version 2018-01-16
 */
@Controller
@RequestMapping(value = "${adminPath}/tms/resource")
public class ResourceController extends BaseController {

	@Autowired
	private ResourceService resourceService;
	
	@ModelAttribute
	public Resource get(@RequestParam(required=false) String id) {
		Resource entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = resourceService.get(id);
		}
		if (entity == null){
			entity = new Resource();
		}
		return entity;
	}
	
	/**
	 * 承运商列表页面
	 */
	@RequiresPermissions("tms:resource:list")
	@RequestMapping(value = {"list", ""})
	public String list() {
		List<Resource> resourceList = resourceService.findList(new Resource());
		for (Resource resource:resourceList) {
			Resource resource1 = new Resource();
			resource1.setName(resource.getName());
			List<Resource> resourceLists = resourceService.findList(resource1);
			if((resourceLists.size())==1){
				resource.setIsrepeat("0");
			}else{
				resource.setIsrepeat("1");

			}
			resourceService.save(resource);
		}
		return "modules/tms/resourceList";
	}
	
		/**
	 * 承运商列表数据
	 */
	@ResponseBody
	@RequiresPermissions("tms:resource:list")
	@RequestMapping(value = "data")
	public Map<String, Object> data(Resource resource, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<Resource> page = resourceService.findPage(new Page<Resource>(request, response), resource); 
		return getBootstrapData(page);
	}

	/**
	 * 查看，增加，编辑承运商表单页面
	 */
	@RequiresPermissions(value={"tms:resource:view","tms:resource:add","tms:resource:edit"},logical=Logical.OR)
	@RequestMapping(value = "form")
	public String form(Resource resource, Model model) {
		model.addAttribute("resource", resource);
		return "modules/tms/resourceForm";
	}

	/**
	 * 保存承运商
	 */
	@ResponseBody
	@RequiresPermissions(value={"tms:resource:add","tms:resource:edit"},logical=Logical.OR)
	@RequestMapping(value = "save")
	public AjaxJson save(Resource resource, Model model, RedirectAttributes redirectAttributes) throws Exception{
		AjaxJson j = new AjaxJson();
		if (!beanValidator(model, resource)){
			j.setSuccess(false);
			j.setMsg("非法参数！");
			return j;
		}
		List<Resource> resourceList = resourceService.findList(resource);
		if (resourceList.size() == 0) {
			resourceService.save(resource);//保存
			j.setSuccess(true);
			j.setMsg("保存承运商成功");
			return j;
		} else {
			int i = 1;
			for (Resource res : resourceList) {
				if ((res.getName()).equals((resource.getName()))) {
					i++;
				}
			}
			if(!resource.getIsNewRecord()){
				int k = 1;
				for (Resource res : resourceList) {
					if ((res.getName()).equals((resource.getName()))&&!((res.getId()).equals((resource.getId())))) {
						k++;
					}
				}
				if (k == 1) {
					resourceService.save(resource);//编辑保存
					j.setSuccess(true);
					j.setMsg("保存承运商成功");
				} else {
					j.setSuccess(false);
					j.setMsg("承运商已存在!");
				}
			}else {
				if (i == 1) {
					resourceService.save(resource);//编辑保存
					j.setSuccess(true);
					j.setMsg("保存承运商成功");
				} else {
					j.setSuccess(false);
					j.setMsg("承运商已存在!");
				}
			}

		}


		return j;
	}
	
	/**
	 * 删除承运商
	 */
	@ResponseBody
	@RequiresPermissions("tms:resource:del")
	@RequestMapping(value = "delete")
	public AjaxJson delete(Resource resource, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		resourceService.delete(resource);
		j.setMsg("删除承运商成功");
		return j;
	}
	
	/**
	 * 批量删除承运商
	 */
	@ResponseBody
	@RequiresPermissions("tms:resource:del")
	@RequestMapping(value = "deleteAll")
	public AjaxJson deleteAll(String ids, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		String idArray[] =ids.split(",");
		for(String id : idArray){
			resourceService.delete(resourceService.get(id));
		}
		j.setMsg("删除承运商成功");
		return j;
	}
	
	/**
	 * 导出excel文件
	 */
	@ResponseBody
	@RequiresPermissions("tms:resource:export")
    @RequestMapping(value = "export", method=RequestMethod.POST)
    public AjaxJson exportFile(Resource resource, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		try {
            String fileName = "承运商"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            Page<Resource> page = resourceService.findPage(new Page<Resource>(request, response, -1), resource);
    		new ExportExcel("承运商", Resource.class).setDataList(page.getList()).write(response, fileName).dispose();
    		j.setSuccess(true);
    		j.setMsg("导出成功！");
    		return j;
		} catch (Exception e) {
			j.setSuccess(false);
			j.setMsg("导出承运商记录失败！失败信息："+e.getMessage());
		}
			return j;
    }

	/**
	 * 导入Excel数据

	 */
	@RequiresPermissions("tms:resource:import")
    @RequestMapping(value = "imports", method=RequestMethod.POST)
    public String importFiles(MultipartFile file, RedirectAttributes redirectAttributes) {
		try {
			int successNum = 0;
			int failureNum = 0;
			StringBuilder failureMsg = new StringBuilder();
			ImportExcel ei = new ImportExcel(file, 1, 0);
			List<Resource> list = ei.getDataList(Resource.class);
			for (Resource resource : list){
				try{
					resourceService.save(resource);
					successNum++;
				}catch(ConstraintViolationException ex){
					failureNum++;
				}catch (Exception ex) {
					failureNum++;
				}
			}
			if (failureNum>0){
				failureMsg.insert(0, "，失败 "+failureNum+" 条承运商记录。");
			}
			addMessage(redirectAttributes, "已成功导入 "+successNum+" 条承运商记录"+failureMsg);
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入承运商失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/tms/resource/?repage";
    }
	
	/**
	 * 下载导入承运商数据模板
	 */
	@RequiresPermissions("tms:resource:import")
    @RequestMapping(value = "import/template")
    public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "承运商数据导入模板.xlsx";
    		List<Resource> list = Lists.newArrayList(); 
    		new ExportExcel("承运商数据", Resource.class, 1).setDataList(list).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入模板下载失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/tms/resource/?repage";
    }

	/**
	 * 承运商导出数据
	 */
	@RequestMapping(value = "exportresource")
	public ModelAndView export(Resource resource, String ids, HttpServletRequest request, HttpServletResponse response) {

		List<Resource> resourceList = new ArrayList<Resource>();

		if(StringUtils.isNotEmpty(ids)){
			String idArray[] = ids.split(",");
			for (String id : idArray) {
				resourceList.add(resourceService.get(id));
			}
		}else{
			resourceList = resourceService.findList(resource);
		}

		try {
			Map<String, Object> dataMap = new HashMap<String, Object>();
			List<String> titles = new ArrayList<String>();
			//添加订单签收标题
			titles.add("公司名称");
			titles.add("联系人");
			titles.add("电话");
			titles.add("手机");
			titles.add("所属园区");
			titles.add("公司地址");
			titles.add("认证类型");
			titles.add("认证日期");
			titles.add("认证到期日期");
			titles.add("保险到期日期");
			titles.add("合同类型");
			titles.add("合同到期日期");
			titles.add("软件品牌");
			titles.add("身份证号");
			titles.add("公司注册时间");
			titles.add("公司简介");
			titles.add("是否置顶");
			titles.add("置顶到期日期");
			titles.add("浏览数");
			titles.add("分享次数");
			titles.add("录入日期");
			titles.add("修改日期");
			dataMap.put("titles", titles);

			List<PageData> excelList = new ArrayList<PageData>();
			//添加表内容
			for (Resource yq : resourceList) {
				PageData map = new PageData();
				map.put("var1", yq.getName());
				if (StringUtils.isNotEmpty(yq.getContacts())) {
					map.put("var2",  yq.getContacts());
				} else {
					map.put("var2", "");
				}
				if (StringUtils.isNotEmpty(yq.getCompanyPhone())) {
					map.put("var3",  yq.getCompanyPhone());
				} else {
					map.put("var3", "");
				}
				if (StringUtils.isNotEmpty(yq.getPhone())) {
					map.put("var4",  yq.getPhone());
				} else {
					map.put("var4", "");
				}
				if (StringUtils.isNotEmpty(yq.getPark())) {
					map.put("var5",  yq.getPark());
				} else {
					map.put("var5", "");
				}
				if (StringUtils.isNotEmpty(yq.getCompanyAddress())) {
					map.put("var6",  yq.getCompanyAddress());
				} else {
					map.put("var6", "");
				}
				if (StringUtils.isNotEmpty(yq.getAuthenticationType())) {
					String authenticationType ="";
					String str[]= yq.getAuthenticationType().split(",");
					for(int i=0; i<str.length; i++){
						if("0".equals(str[i])){
							authenticationType+="认证,";
						}
						if("1".equals(str[i])){
							authenticationType+="精品,";
						}
						if("2".equals(str[i])){
							authenticationType+="保险,";
						}
						if("3".equals(str[i])){
							authenticationType+="保证金,";
						}
					}
					map.put("var7",  authenticationType);
				} else {
					map.put("var7", "");
				}
				if ((yq.getCertificationDate())!=null) {
					map.put("var8",  DateUtils.formatDate(yq.getCertificationDate(), "yyyy-MM-dd HH:mm:ss"));
				} else {
					map.put("var8", "");
				}
				if ((yq.getExpirationDate())!=null) {
					map.put("var9",  DateUtils.formatDate(yq.getExpirationDate(), "yyyy-MM-dd HH:mm:ss"));
				} else {
					map.put("var9", "");
				}
				if ((yq.getInsuranceDate())!=null) {
					map.put("var10",  DateUtils.formatDate(yq.getInsuranceDate(), "yyyy-MM-dd HH:mm:ss"));
				} else {
					map.put("var10", "");
				}
				if (StringUtils.isNotEmpty(yq.getCooperationType())) {
					if("0".equals(yq.getCooperationType())){
						map.put("var11",  "否");
					}
					if("1".equals(yq.getCooperationType())) {
						map.put("var11", "是");
					}
				} else {
					map.put("var11", "");
				}
				if ((yq.getCooperationDate())!=null) {
					map.put("var12",  DateUtils.formatDate(yq.getCooperationDate(), "yyyy-MM-dd HH:mm:ss"));
				} else {
					map.put("var12", "");
				}
				if (StringUtils.isNotEmpty(yq.getBrand())) {
					map.put("var13",  yq.getBrand());
				} else {
					map.put("var13", "");
				}
				if (StringUtils.isNotEmpty(yq.getIdCard())) {
					map.put("var14",  yq.getIdCard());
				} else {
					map.put("var14", "");
				}
				if ((yq.getRegisterDate())!=null) {
					map.put("var15",  DateUtils.formatDate(yq.getRegisterDate(), "yyyy-MM-dd HH:mm:ss"));
				} else {
					map.put("var15", "");
				}
				if (StringUtils.isNotEmpty(yq.getCompanySummary())) {
					map.put("var16",  yq.getCompanySummary());
				} else {
					map.put("var16", "");
				}
				if (StringUtils.isNotEmpty(yq.getTop())) {
					if(yq.getTop().equals("0")){
						map.put("var17",  "否");
					}
					if(yq.getTop().equals("1")){
						map.put("var17",  "是");
					}
				} else {
					map.put("var17", "");
				}
				if ((yq.getTopDate())!=null) {
					map.put("var18",  DateUtils.formatDate(yq.getTopDate(), "yyyy-MM-dd HH:mm:ss"));
				} else {
					map.put("var18", "");
				}
				if (StringUtils.isNotEmpty(yq.getSkimAmount())) {
					map.put("var19",  yq.getSkimAmount());
				} else {
					map.put("var19", "");
				}
				if (StringUtils.isNotEmpty(yq.getSharingTimes())) {
					map.put("var20",  yq.getSharingTimes());
				} else {
					map.put("var20", "");
				}
				if ((yq.getCreateDate())!=null) {
					map.put("var21",  DateUtils.formatDate(yq.getCreateDate(), "yyyy-MM-dd HH:mm:ss"));
				} else {
					map.put("var21", "");
				}
				if ((yq.getUpdateDate())!=null) {
					map.put("var22",  DateUtils.formatDate(yq.getUpdateDate(), "yyyy-MM-dd HH:mm:ss"));
				} else {
					map.put("var22", "");
				}
				excelList.add(map);

			}
				String fileName = "承运商"+ DateUtils.formatDate(new Date(), "yyyy-MM-dd ");
				dataMap.put("fileName",fileName);

			dataMap.put("excelList", excelList);
			System.out.println("===导出excel成功！");
			ObjectExcelView erv = new ObjectExcelView();                    //执行excel操作

			return new ModelAndView(erv, dataMap);

		} catch(Exception e) {
			System.out.println("======导出excel时出错！" + e.getMessage());
		}
		return new ModelAndView("redirect:" + Global.getAdminPath() + "/tms/resourceList");
	}

	/**
	 * 导入Excel数据
	 */
	@RequiresPermissions("tms:dropDispatch:import")
	@RequestMapping(value = "import", method = RequestMethod.POST)
	public String importFile(MultipartFile file, RedirectAttributes redirectAttributes) {
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
		try {
			int successNum = 0;
			int failureNum = 0;
			StringBuilder failureMsg = new StringBuilder();
			ImportExcel ei = new ImportExcel(file, 1, 0);
			List<ResourceImport> newList = ei.getDataList(ResourceImport.class);
			for (ResourceImport ddi : newList) {
				try {
					Resource resource = new Resource();
					if (StringUtils.isNotEmpty(ddi.getName())) {
						resource.setName(ddi.getName());
					}
					if (StringUtils.isNotEmpty(ddi.getContacts())) {
						resource.setContacts(ddi.getContacts());
					}
					if (StringUtils.isNotEmpty(ddi.getCompanyPhone())) {
						resource.setCompanyPhone(ddi.getCompanyPhone());
					}
					if (StringUtils.isNotEmpty(ddi.getPhone())) {
						resource.setPhone(ddi.getPhone());
					}
					if (StringUtils.isNotEmpty(ddi.getPark())) {
						resource.setPark(ddi.getPark());
					}
					if (StringUtils.isNotEmpty(ddi.getCompanyAddress())) {
						resource.setCompanyAddress(ddi.getCompanyAddress());
					}
					if (StringUtils.isNotEmpty(ddi.getAuthenticationType())) {
						String authenticationType="";
						String str[]= ddi.getAuthenticationType().split(",");
						for(int i=0; i<str.length; i++){
							if("认证".equals(str[i])){
								authenticationType+="0,";
							}
							if("精品".equals(str[i])){
								authenticationType+="1,";
							}
							if("保险".equals(str[i])){
								authenticationType+="2,";
							}
							if("保证金".equals(str[i])){
								authenticationType+="3,";
							}
						}
						resource.setAuthenticationType(authenticationType);
					}
					if (StringUtils.isNotEmpty(ddi.getCertificationDate())) {
						resource.setCertificationDate(df.parse(ddi.getCertificationDate()));
					}
					if (StringUtils.isNotEmpty(ddi.getExpirationDate())) {
						resource.setExpirationDate(df.parse(ddi.getExpirationDate()));
					}
					if (StringUtils.isNotEmpty(ddi.getInsuranceDate())) {
						resource.setInsuranceDate(df.parse(ddi.getInsuranceDate()));
					}
					if (StringUtils.isNotEmpty(ddi.getCooperationType())) {
						if("否".equals(ddi.getCooperationType())){
							resource.setCooperationType("0");
						}else if("是".equals(ddi.getCooperationType())) {
							resource.setCooperationType("1");
						}else {
							resource.setCooperationType("");
						}
					}
					if (StringUtils.isNotEmpty(ddi.getCooperationDate())) {
						resource.setCooperationDate(df.parse(ddi.getCooperationDate()));
					}
					if (StringUtils.isNotEmpty(ddi.getBrand())) {
						resource.setBrand(ddi.getBrand());
					}
					if (StringUtils.isNotEmpty(ddi.getIdCard())) {
						resource.setIdCard(ddi.getIdCard());
					}
					if (StringUtils.isNotEmpty(ddi.getRegisterDate())) {
						resource.setRegisterDate(df.parse(ddi.getRegisterDate()));
					}
					if (StringUtils.isNotEmpty(ddi.getCompanySummary())) {
						resource.setCompanySummary(ddi.getCompanySummary());
					}
					if (StringUtils.isNotEmpty(ddi.getTop())) {
						if (ddi.getTop().equals("否")) {
							resource.setTop("0");
						}else if (ddi.getTop().equals("是")) {
							resource.setTop("1");
						}else{
							resource.setTop("");
						}

					}
					if ((ddi.getTopDate())!=null) {
						resource.setTopDate(df.parse(ddi.getTopDate()));
					}
					resourceService.save(resource);
					successNum++;
				} catch (ConstraintViolationException ex) {
					failureNum++;
				} catch (Exception ex) {
					failureNum++;
				}
			}
			if (failureNum > 0) {
				failureMsg.insert(0, "，失败 " + failureNum + " 条订单记录。失败原因例如：导入数据出错！");
			}
			addMessage(redirectAttributes, "已成功导入 " + successNum + " 条订单记录" + failureMsg);
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入订单失败！失败信息：" + e.getMessage());
		}
		return "redirect:" + Global.getAdminPath() + "/tms/resource/?repage";
	}
}